// 看板功能手动测试脚本
// 在浏览器控制台中运行

async function testKanbanFunctionality() {
  console.log('🧪 开始看板功能测试');
  console.log('='.repeat(50));
  
  const API_BASE = 'http://localhost:5000/api';
  const results = { passed: 0, failed: 0, total: 0 };
  
  function logTest(name, success, message = '') {
    results.total++;
    const status = success ? '✅' : '❌';
    const msg = message ? ` - ${message}` : '';
    console.log(`${status} ${name}${msg}`);
    if (success) results.passed++;
    else results.failed++;
  }
  
  try {
    // 测试1: 登录
    console.log('\n🔐 测试1: 用户登录');
    const loginResponse = await fetch(`${API_BASE}/auth/login/email`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: 'admin@aide.com',
        password: 'admin123456'
      })
    });
    
    if (loginResponse.ok) {
      const loginData = await loginResponse.json();
      if (loginData.success && loginData.token) {
        logTest('用户登录', true, '获取到认证token');
        window.testToken = loginData.token;
      } else {
        logTest('用户登录', false, '登录响应格式错误');
        return;
      }
    } else {
      const errorData = await loginResponse.text();
      logTest('用户登录', false, `HTTP ${loginResponse.status}: ${errorData}`);
      return;
    }
    
    // 测试2: 获取看板数据
    console.log('\n📊 测试2: 获取看板数据');
    const kanbanResponse = await fetch(`${API_BASE}/kanban`, {
      headers: { 'Authorization': `Bearer ${window.testToken}` }
    });
    
    if (kanbanResponse.ok) {
      const kanbanData = await kanbanResponse.json();
      if (kanbanData.success && kanbanData.data) {
        const { columns, tasks } = kanbanData.data;
        const taskCounts = {
          todo: tasks.todo?.length || 0,
          in_progress: tasks.in_progress?.length || 0,
          review: tasks.review?.length || 0,
          done: tasks.done?.length || 0
        };
        logTest('获取看板数据', true, `${columns.length}列，任务分布: ${JSON.stringify(taskCounts)}`);
        window.testKanbanData = kanbanData.data;
      } else {
        logTest('获取看板数据', false, '数据结构不完整');
      }
    } else {
      logTest('获取看板数据', false, `HTTP ${kanbanResponse.status}`);
    }
    
    // 测试3: 创建测试任务
    console.log('\n📝 测试3: 创建测试任务');
    const createResponse = await fetch(`${API_BASE}/tasks`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${window.testToken}`
      },
      body: JSON.stringify({
        title: '测试拖拽任务',
        description: '用于测试看板拖拽功能的任务',
        priority: 'P1',
        category: 'work',
        status: 'todo'
      })
    });
    
    if (createResponse.ok) {
      const createData = await createResponse.json();
      if (createData.id) {
        logTest('创建测试任务', true, `任务ID: ${createData.id}`);
        window.testTaskId = createData.id;
      } else {
        logTest('创建测试任务', false, '未返回任务ID');
      }
    } else {
      const errorData = await createResponse.text();
      logTest('创建测试任务', false, `HTTP ${createResponse.status}: ${errorData}`);
    }
    
    // 测试4: 任务状态更新 (模拟拖拽)
    if (window.testTaskId) {
      console.log('\n🎯 测试4: 任务状态更新 (模拟拖拽)');
      
      // 测试拖拽到进行中
      const updateResponse = await fetch(`${API_BASE}/kanban/tasks/${window.testTaskId}/status`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${window.testToken}`
        },
        body: JSON.stringify({
          status: 'in_progress',
          position: 0
        })
      });
      
      if (updateResponse.ok) {
        const updateData = await updateResponse.json();
        if (updateData.success) {
          logTest('任务状态更新', true, updateData.message);
          
          // 验证更新结果
          console.log('\n🔍 测试5: 验证状态更新');
          await new Promise(resolve => setTimeout(resolve, 500)); // 等待数据同步
          
          const verifyResponse = await fetch(`${API_BASE}/kanban`, {
            headers: { 'Authorization': `Bearer ${window.testToken}` }
          });
          
          if (verifyResponse.ok) {
            const verifyData = await verifyResponse.json();
            if (verifyData.success) {
              const inProgressTasks = verifyData.data.tasks.in_progress || [];
              const movedTask = inProgressTasks.find(task => task.id === window.testTaskId);
              
              if (movedTask) {
                logTest('验证状态更新', true, '任务已正确移动到进行中列');
              } else {
                logTest('验证状态更新', false, '任务未找到在进行中列');
              }
            } else {
              logTest('验证状态更新', false, '验证响应格式错误');
            }
          } else {
            logTest('验证状态更新', false, `验证请求失败: HTTP ${verifyResponse.status}`);
          }
          
        } else {
          logTest('任务状态更新', false, updateData.error || '更新失败');
        }
      } else {
        const errorData = await updateResponse.text();
        logTest('任务状态更新', false, `HTTP ${updateResponse.status}: ${errorData}`);
      }
    }
    
    // 清理测试任务
    if (window.testTaskId) {
      console.log('\n🧹 清理测试任务');
      try {
        await fetch(`${API_BASE}/tasks/${window.testTaskId}`, {
          method: 'DELETE',
          headers: { 'Authorization': `Bearer ${window.testToken}` }
        });
        console.log('✅ 测试任务已清理');
      } catch (error) {
        console.log('⚠️ 清理测试任务失败:', error.message);
      }
    }
    
  } catch (error) {
    console.error('❌ 测试执行失败:', error);
    logTest('测试执行', false, error.message);
  }
  
  // 生成测试报告
  console.log('\n📋 测试报告');
  console.log('='.repeat(50));
  console.log(`总测试数: ${results.total}`);
  console.log(`通过: ${results.passed} ✅`);
  console.log(`失败: ${results.failed} ❌`);
  
  const successRate = Math.round((results.passed / results.total) * 100);
  console.log(`成功率: ${successRate}%`);
  
  const status = successRate >= 80 ? 'PASS' : 'FAIL';
  console.log(`\n🎯 总体状态: ${status}`);
  
  if (status === 'PASS') {
    console.log('🎉 看板功能测试通过！拖拽功能正常工作。');
  } else {
    console.log('⚠️ 看板功能存在问题，需要进一步检查。');
  }
  
  return { status, successRate, ...results };
}

// 导出测试函数
if (typeof window !== 'undefined') {
  window.testKanbanFunctionality = testKanbanFunctionality;
  console.log('🔧 测试函数已加载');
  console.log('📋 使用方法: 在浏览器控制台运行 testKanbanFunctionality()');
} else {
  console.log('⚠️ 此脚本需要在浏览器环境中运行');
}
